package com.itheima.reggie.controlle;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 */
@RestController
@RequestMapping("category")
public class CategoryController {

    //注入ioc bean
    @Autowired
    CategoryService categoryService;

    /**
     * 新增菜品或套餐
     * 返回值字符串
     * post请求参数对象接收
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * 分页查询
     * @param
     * @return
     */
    @GetMapping("/page")
    public R<Page<Category>> page(@RequestParam("page") Integer page,
                                  @RequestParam("pageSize") Integer pageSize) {
        Page<Category> pages = categoryService.pages(page, pageSize);
        return R.success(pages);
    }

    /**
     * 修改
     */
    @PutMapping
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("");
    }

    /**
     * 根据id删除
     * 没有请求体参数直接填前端对应key
     */
    @DeleteMapping
    public R<String> deleteById(@RequestParam("id") Long id){
        categoryService.deleteById(id);
        return R.success("");
    }

    /**
     * 判断分类类型
     * 返回值list集合数据
     * 参数type
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        //判断type属性并排序
        LambdaQueryWrapper<Category> queryWrapper = Wrappers.lambdaQuery(Category.class)
                .eq(category.getType()!=null, Category::getType, category.getType())
                .orderByAsc(Category::getSort)
                .orderByDesc(Category::getUpdateTime);
        List<Category> categoryList = categoryService.list(queryWrapper);
        //返回集合数据
        return R.success(categoryList);
    }
}
